<template>
  <div>
    <el-dialog
      title="封面和商品图片"
      :visible.sync="coverImgDialogFormVisible"
      width="800px"
      :modal-append-to-body="true"
      :append-to-body="true"
    >
      <el-form
        class="dialog-form"
        ref="stockDialogRulesForm"
        :model="goodsCoverData"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="封面" prop="cover">
          <el-upload
            class="avatar-uploader"
            :action="UPLOAD_URL"
            :show-file-list="false"
            :on-success="handleUploadCoverSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="goodsCoverData.cover" :src="goodsCoverData.cover|absUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品图片" prop="otherImgs">
          <xd-upload v-model="goodsCoverData.otherImgs"></xd-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sureSelectPic">确定</el-button>
      </div>
    </el-dialog>
    <template v-if="goodsRules.length">
      <el-card class="box-card" v-for="(goodRule,index) in goodsRules" :key="index">
        <div slot="header" class="clearfix">
          <el-input
            v-model="goodRule.title"
            :ref="'goodsRuleInput'+index"
            placeholder="请输入商品规格名称(比如颜色)"
            style="width:250px;"
          ></el-input>&nbsp;&nbsp;&nbsp;&nbsp;
          <!-- <el-checkbox v-model="goodRule.hasPic" @change="changeHasPic(goodRule,index)">添加图片</el-checkbox> -->
          <i class="el-icon-close close-btn right-icon" @click="removeRule(index)"></i>
        </div>
        <div class="el-tag-wrapper" :key="yindex" v-for="(item,yindex) in goodRule.items">
          <el-tag
            closable
            @click="editRuleItem(item)"
            :disable-transitions="false"
            class="my-el-tag"
            @close="handleClose(index,yindex)"
          >{{item.title}}</el-tag>
        </div>
        <div class="el-tag-wrapper">
          <el-input
            class="input-new-tag"
            v-show="goodRule.inputVisible"
            v-model="goodRule.inputValue"
            :ref="'saveTagInput'+index"
            size="small"
            @keyup.enter.native="handleInputConfirm(index)"
            @blur="handleInputConfirm(index)"
            :focus="true"
          ></el-input>
          <el-button
            class="button-new-tag"
            v-if="!goodRule.inputVisible && goodRule.items.length<9"
            size="small"
            @click="showInput(index)"
          >
            +
            添加规格
          </el-button>
        </div>
      </el-card>
    </template>
    <template v-else-if="defaultSku">
      <div class="default-sku">
        <el-form
          :rules="rules"
          ref="dataForm2"
          :model="defaultSku"
          label-position="left"
          label-width="120px"
        >
          <el-row :gutter="18">
            <el-col :span="20">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="商品名称" prop="title">
                    <el-input placeholder="请输入商品名称" v-model="defaultSku.title" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品编码" prop="goodsNo">
                    <el-input
                      placeholder="请输入商品编码"
                      @change="handleChangeGoodsNo(-1)"
                      v-model="defaultSku.goodsNo"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="条形码" prop="barCode">
                    <el-input placeholder="请输入条形码" v-model="defaultSku.barCode" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="市场价" prop="marketPrice">
                    <el-input-number v-model="defaultSku.marketPrice" placeholder="市场价"></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="微信价" prop="price">
                    <el-input-number
                      :disabled="isEditingDefaultSku && !isAdmin()"
                      placeholder="请输入微信价"
                      v-model="defaultSku.price"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="积分价" prop="points">
                    <el-input-number
                      :disabled="isEditingDefaultSku && !isAdmin()"
                      placeholder="请输入积分价"
                      v-model="defaultSku.points"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="库存" prop="stock">
                    <el-input-number
                      placeholder="请输入库存"
                      :disabled="isEditingDefaultSku"
                      v-model="defaultSku.stock"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="预警库存" prop="alertStock">
                    <el-input-number
                      :disabled="isEditingDefaultSku && !isAdmin()"
                      placeholder="请输入预警库存"
                      v-model="defaultSku.alertStock"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="4">
              封面与商品图片
              <div class="avatar-uploader-3" @click="showPicPickerDialog(-1)">
                <img v-if="defaultSku.cover" :src="defaultSku.cover|absUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </template>
    <el-button
      type="primary"
      v-if="goodsRules.length<3"
      size="small"
      icon="el-icon-plus"
      @click="addNewGoodRule"
    >添加商品规格</el-button>
    <div class="price-and-stock" v-if="hasValidRules">
      <table>
        <thead>
          <tr class="batch">
            <td rowspan="2" :colspan="hasValidRules">批量修改</td>
            <td width="140">市场价</td>
            <td width="140">微信价</td>
            <td width="140">积分价</td>
            <td width="140">库存</td>
            <td width="140">预警库存</td>
            <td colspan="2" rowspan="2"></td>
          </tr>
          <tr class="batch">
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchMarketPrice" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchPrice" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchPoints" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchStock" :min="0"></el-input-number>
            </td>
            <td>
              <el-input-number class="numberbox" size="mini" v-model="batchalertStock" :min="0"></el-input-number>
            </td>
          </tr>
          <tr>
            <th
              v-for="(goodRule,index) in goodsRules"
              :key="index"
              v-if="goodRule.items && goodRule.items.length"
            >{{goodRule.title}}</th>
            <th colspan="3">标题</th>
            <th colspan="1">商品编码</th>
            <th colspan="1">条形码</th>
            <!-- <th width="100">封面</th> -->
            <th width="100">图片</th>
            <th width="90">启用</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="(row,index) in goodsRulePrices">
            <tr :key="index">
              <td
                v-for="(value,field) in row"
                :key="field"
                v-if="value.rowSpan"
                :rowspan="value.rowSpan"
              >{{value.title}}</td>
              <td colspan="3" :class="{disabled_tr:!enabledMap[row._key]}">
                <el-input
                  class="goods-title"
                  placeholder="请输入标题"
                  :disabled="!enabledMap[row._key]"
                  v-model="titleMap[row._key]"
                  size="mini"
                />
              </td>
              <td colspan="1" :class="{disabled_tr:!enabledMap[row._key]}">
                <el-input
                  type="text"
                  class="goods-title"
                  placeholder="请输入商品编码"
                  @change="handleChangeGoodsNo(row._key)"
                  :disabled="!enabledMap[row._key]"
                  v-model="goodsNoMap[row._key]"
                  size="mini"
                />
              </td>
              <td colspan="1" :class="{disabled_tr:!enabledMap[row._key]}">
                <el-input
                  type="text"
                  class="goods-title"
                  :disabled="!enabledMap[row._key]"
                  placeholder="请输入条形码"
                  v-model="barCodeMap[row._key]"
                  size="mini"
                />
              </td>
              <!-- <td> -->
              <!-- <el-upload  class="avatar-uploader" :action="UPLOAD_URL" :show-file-list="false" :on-success="handleUploadSuccess"
            :before-upload="beforeAvatarUpload">
                <img v-if="coverMap[index]" :src="coverMap[index]|absUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>-->

              <!-- </td> -->
              <td rowspan="3" :class="{disabled_tr:!enabledMap[row._key]}">
                <div
                  class="avatar-uploader-3"
                  @click="enabledMap[row._key] && showPicPickerDialog(row._key)"
                >
                  <img v-if="coverMap[row._key]" :src="coverMap[row._key]|absUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </div>
              </td>
              <td rowspan="3">
                <el-checkbox v-model="enabledMap[row._key]">启用</el-checkbox>
              </td>
            </tr>
            <tr :key="index+'_1'" :class="{disabled_tr:!enabledMap[row._key]}">
              <td width="140">市场价</td>
              <td width="140">微信价</td>
              <td width="140">积分价</td>
              <td width="140">库存</td>
              <td width="140">预警库存</td>
            </tr>
            <tr :key="index+'_2'" :class="{disabled_tr:!enabledMap[row._key]}">
              <td>
                <el-input-number
                  class="numberbox"
                  :disabled="!enabledMap[row._key]"
                  size="mini"
                  v-model="marketPriceMap[row._key]"
                  :min="0"
                ></el-input-number>
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || (editableMap[row._key] && !isAdmin())"
                  class="numberbox"
                  size="mini"
                  v-model="priceMap[row._key]"
                  :min="0"
                ></el-input-number>
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || (editableMap[row._key] && !isAdmin())"
                  class="numberbox"
                  size="mini"
                  v-model="pointsMap[row._key]"
                  :min="0"
                ></el-input-number>
              </td>
              <td>
                <el-input-number
                  :disabled="!enabledMap[row._key] || editableMap[row._key]"
                  class="numberbox"
                  size="mini"
                  v-model="stockMap[row._key]"
                  :min="0"
                ></el-input-number>
              </td>
              <td>
                <el-input-number
                  class="numberbox"
                  size="mini"
                  :disabled="!enabledMap[row._key] || (editableMap[row._key] && !isAdmin())"
                  v-model="alertStockMap[row._key]"
                  :min="0"
                ></el-input-number>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
import xdUploadVue from '../components/xdUpload.vue';
export default {
  components: {
    'xd-upload': xdUploadVue
  },
  data () {
    return {
      enabledMap: {},
      editableMap: {},
      rmsPriceMap: {},
      batchGoodsNo: '',
      batchMarketPrice: 0,
      batchPoints: 0,
      isEditingDefaultSku: false,
      goodsCoverData: {
        cover: '',
        otherImgs: ''
      },
      batchStock: 0,
      batchalertStock: 0,
      otherImgsMap: {},
      batchPrice: 0,
      coverImgDialogFormVisible: false,
      goodsRules: [],
      pointsMap: {},
      marketPriceMap: {},
      titleMap: {},
      defaultSku: null,
      coverMap: {},
      priceMap: {},
      stockMap: {},
      alertStockMap: {},
      goodsNoMap: {},
      barCodeMap: {},
      rules: {
        title: [
          {
            required: true,
            message: '商品名称不能为空',
            trigger: 'change'
          },
          {
            max: 60,
            message: '商品名称不能大于60个字',
            trigger: 'change'
          }
        ],
        price: [
          {
            required: true,
            message: '微信价不能为空',
            trigger: 'change'
          }
        ],

        points: [
          {
            required: true,
            message: '积分价不能为空',
            trigger: 'change'
          }
        ],

        goodsNo: [
          {
            required: true,
            message: '商品编码不能为空',
            trigger: 'change',
            max: 60
          }
        ],

        stock: [
          {
            required: true,
            message: '商品库存不能为空',
            trigger: 'change'
          }
        ],

        alertStock: [
          {
            required: true,
            message: '警戒库存不能为空',
            trigger: 'change'
          }
        ],
        marketPrice: [
          {
            required: true,
            message: '市场价不能为空',
            trigger: 'change'
          }
        ]
      }
    }
  },
  // model: {
  //   prop: "goodsRuleValues",
  //   event: "changeGoodsRuleValues"
  // },
  // props: {
  //   goodsRuleValues: null
  // },
  watch: {
    // goodsRuleValues() {
    //   this.initData();
    // },
    batchPrice () {
      for (let key in this.priceMap) {
        this.priceMap[key] = this.batchPrice
      }
    },
    batchMarketPrice () {
      for (let key in this.marketPriceMap) {
        this.marketPriceMap[key] = this.batchMarketPrice
      }
    },
    batchPoints () {
      for (let key in this.pointsMap) {
        this.pointsMap[key] = this.batchPoints
      }
    },
    batchStock () {
      for (let key in this.stockMap) {
        this.stockMap[key] = this.batchStock
      }
    },
    batchalertStock () {
      for (let key in this.alertStockMap) {
        this.alertStockMap[key] = this.batchalertStock
      }
    }
    // ,
    // batchGoodsNo() {
    //   for (let key in this.goodsNoMap) {
    //       this.goodsNoMap[key] = this.batchGoodsNo;
    //   }
    // }
  },
  computed: {
    hasValidRules () {
      let rt = 0
      this.goodsRules.forEach(el => {
        if (el.items && el.items.length > 0) {
          rt++
        }
      })
      return rt
    },
    goodsRulePrices () {
      let rowCount = 0
      for (let i = 0; i < this.goodsRules.length; i++) {
        if (this.goodsRules[i].items.length > 0) {
          if (rowCount == 0) {
            rowCount = 1
          }
          rowCount *= this.goodsRules[i].items.length
        }
      }
      let rows = []
      if (rowCount > 0) {
        // rowCount*=2;
        for (let i = 0; i < rowCount; i++) {
          rows.push([])
        }
        let groupCount = 1 // 分组
        let colIndex = 0
        for (let i = 0; i < this.goodsRules.length; i++) {
          let rule = this.goodsRules[i]
          let items = rule.items
          if (items && items.length) {
            let rowSpan = rowCount / items.length / groupCount
            let groupSize = rowCount / groupCount
            for (let g = 0; g < groupCount; g++) {
              for (let j = 0; j < items.length; j++) {
                for (let k = 0; k < rowSpan; k++) {
                  rows[groupSize * g + j * rowSpan + k][colIndex] = {
                    title: items[j].title,
                    index: j,
                    rowSpan: k === 0 ? rowSpan * 3 : 0
                  }
                }
              }
            }
            groupCount *= items.length
            colIndex++
          }
        }
      }
      rows.forEach(row => {
        const idx = this.parse2Key(row)
        row._key = idx
        this.goodsNoMap[idx] || this.$set(this.goodsNoMap, idx, '')
        this.barCodeMap[idx] || this.$set(this.barCodeMap, idx, '')
        this.coverMap[idx] || this.$set(this.coverMap, idx, '')
        this.otherImgsMap[idx] || this.$set(this.otherImgsMap, idx, '')
        this.stockMap[idx] || this.$set(this.stockMap, idx, this.batchStock)
        this.priceMap[idx] || this.$set(this.priceMap, idx, this.batchPrice)
        this.pointsMap[idx] || this.$set(this.pointsMap, idx, this.batchPoints)
        this.alertStockMap[idx] ||
          this.$set(this.alertStockMap, idx, this.batchalertStock)
        this.marketPriceMap[idx] ||
          this.$set(this.marketPriceMap, idx, this.batchMarketPrice)
        idx in this.enabledMap || this.$set(this.enabledMap, idx, true)
      })
      return rows
    }
  },
  methods: {
    handleChangeGoodsNo (idx) {
      let goodsNo
      if (idx === -1) {
        goodsNo = this.defaultSku.goodsNo
      } else {
        goodsNo = this.goodsNoMap[idx]
      }
      this.$post('/admin/goods/sync_rms_goods_data', {
        goodsNo
      }).then(data => {
        if (data && data.length) {
          data = data[0]
          this.rmsPriceMap[idx] = data
          if (idx === -1) {
            this.defaultSku.barCode = this.defaultSku.barCode || data.barcodeid
            this.defaultSku.title = this.defaultSku.title || data.name
            this.defaultSku.price = parseFloat(data.price)
            this.defaultSku.marketPrice = parseFloat(
              this.defaultSku.marketPrice || data.normalprice
            )
            this.$set(this.defaultSku, 'price', this.defaultSku.price)
            this.$set(this.defaultSku, 'title', this.defaultSku.title)
          } else {
            this.priceMap[idx] = parseFloat(data.price)
            this.barCodeMap[idx] = this.barCodeMap[idx] || data.barcodeid
            this.$set(this.titleMap, idx, this.titleMap[idx] || data.name)
            this.marketPriceMap[idx] = parseFloat(
              this.marketPriceMap[idx] || data.normalprice
            )
          }
        }
      })
    },
    parse2Key (row) {
      const data = {}
      for (let i = 0; i < row.length; i++) {
        data[this.goodsRules[i].title] = row[i].title
      }
      return JSON.stringify(data)
    },
    editRuleItem (item) {
      console.log(item)
    },
    showPicPickerDialog (idx) {
      this.coverImgDialogFormVisible = true
      if (idx < 0) {
        this.goodsCoverData.cover = this.defaultSku.cover
        this.goodsCoverData.otherImgs = this.defaultSku.otherImgs
      } else {
        this.goodsCoverData.cover = this.coverMap[idx]
        this.goodsCoverData.otherImgs = this.otherImgsMap[idx]
      }
      this.goodsCoverData.idx = idx
    },
    valid () {
      let rt = false
      if (this.$refs['dataForm2']) {
        this.$refs['dataForm2'].validate(valid => {
          if (valid) {
            rt = true
          }
        })
      } else {
        rt = true
      }
      const errmsgList = []
      // todo
      for (const key in this.rmsPriceMap) {
        let price
        let points
        let title
        const rmsPrice = this.rmsPriceMap[key].price
        if (key == -1) {
          price = this.defaultSku.price
          points = this.defaultSku.points
          title = this.defaultSku.title
        } else {
          price = this.priceMap[key]
          points = this.pointsMap[key]
          title = this.titleMap[key]
        }
        if (price - 0 + points * 0.2 != rmsPrice) {
          errmsgList.push(
            '商品【' + title + '】微信价+积分*0.2不等于RMS的商品价格'
          )
        }
      }
      return new Promise((resolve, reject) => {
        if (errmsgList.length > 0) {
          this.$confirm(
            errmsgList.join('<br/>') + '<br/>是否继续提交?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              type: 'warning'
            }
          )
            .then(() => {
              resolve()
            })
            .catch(() => {
              // eslint-disable-next-line prefer-promise-reject-errors
              reject()
            })
        } else {
          if (rt) {
            resolve()
          } else {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject()
          }
        }
      })
    },
    sureSelectPic () {
      this.coverImgDialogFormVisible = false
      if (this.goodsCoverData.idx < 0) {
        this.defaultSku.cover = this.goodsCoverData.cover
        this.defaultSku.otherImgs = this.goodsCoverData.otherImgs
      } else {
        this.coverMap[this.goodsCoverData.idx] = this.goodsCoverData.cover
        this.otherImgsMap[
          this.goodsCoverData.idx
        ] = this.goodsCoverData.otherImgs
      }
    },
    getData () {
      let skuList = []
      const rowCount = this.goodsRulePrices.length
      if (rowCount > 0) {
        for (let i = 0; i < rowCount; i++) {
          const row = this.goodsRulePrices[i]
          const key = this.parse2Key(row)
          if (!this.enabledMap[key]) {
            continue
          }
          skuList.push({
            goodsNo: this.goodsNoMap[key] || '',
            barCode: this.barCodeMap[key] || '',
            marketPrice: this.marketPriceMap[key] || 0,
            price: this.priceMap[key] || 0,
            points: this.pointsMap[key] || 0,
            saleProps: key,
            stock: this.stockMap[key] || 0,
            alertStock: this.alertStockMap[key] || 0,
            cover: this.coverMap[key] || '',
            otherImgs: this.otherImgsMap[key] || '',
            title: this.titleMap[key] || ''
          })
        }
      } else {
        skuList.push({
          goodsNo: this.defaultSku.goodsNo,
          barCode: this.defaultSku.barCode,
          marketPrice: this.defaultSku.marketPrice,
          price: this.defaultSku.price,
          points: this.defaultSku.points,
          saleProps: '',
          stock: this.defaultSku.stock,
          alertStock: this.defaultSku.alertStock,
          cover: this.defaultSku.cover,
          otherImgs: this.defaultSku.otherImgs,
          title: this.defaultSku.title
        })
      }
      return skuList
    },
    initData (goodsRuleValues) {
      console.log('initData')
      let data = goodsRuleValues
      this.goodsRules = []
      this.pointsMap = {}
      this.marketPriceMap = {}
      this.priceMap = {}
      this.stockMap = {}
      this.alertStockMap = {}
      this.goodsNoMap = {}
      this.barCodeMap = {}
      this.titleMap = {}
      this.coverMap = {}
      this.otherImgsMap = {}
      if (
        data &&
        data.length === 1 &&
        (data[0].saleProps === '' || data[0].saleProps === '{}')
      ) {
        // 没有规格的商品，默认特殊处理
        this.isEditingDefaultSku = true
        this.defaultSku = data[0]
        return;
      }
      if (!data || data.length === 0) {
        // 新增
        this.isEditingDefaultSku = false
        this.defaultSku = {
          goodsNo: '',
          barCode: '',
          marketPrice: 0,
          title: '',
          price: 0,
          stock: 0,
          alertStock: 0,
          points: 0
        }
      }
      if (data && data.length) {
        const mapData = {}
        data.forEach((d, idx) => {
          let props = d.saleProps
          if (props) {
            // for
            props = JSON.parse(props)
            if (!this.goodsRules.length) {
              Object.keys(props).forEach(e => {
                this.goodsRules.push({
                  title: e,
                  inputVisible: false,
                  inputValue: '',
                  items: []
                })
              }) // for rule
            }
            Object.keys(props).forEach(e => {
              const items = this.goodsRules.filter(i => i.title === e)[0].items
              if (!items.some(el => el.title === props[e])) {
                items.push({
                  title: props[e]
                })
              }
            })
            mapData[JSON.stringify(props)] = d
          }
        })
        let rowCount = 0
        for (let i = 0; i < this.goodsRules.length; i++) {
          if (this.goodsRules[i].items.length > 0) {
            if (rowCount === 0) {
              rowCount = 1
            }
            rowCount *= this.goodsRules[i].items.length
          }
        }
        const tempArr = []
        let groupCount = 1 // 分组
        for (let i = 0; i < this.goodsRules.length; i++) {
          let rule = this.goodsRules[i]
          let items = rule.items
          if (items && items.length) {
            let groupSize = rowCount / groupCount
            let len = rowCount / items.length / groupCount
            for (let k = 0; k < groupCount; k++) {
              for (let j = 0; j < items.length; j++) {
                for (let h = 0; h < len; h++) {
                  let idx = k * groupSize + h + j * len
                  if (!tempArr[idx]) {
                    tempArr[idx] = {}
                  }
                  tempArr[idx][rule.title] = items[j].title
                }
              }
            }
            groupCount *= items.length
          }
        }
        tempArr.forEach(el => {
          const key = JSON.stringify(el)
          const d = mapData[key]
          const idx = key
          if (d) {
            this.stockMap[idx] = d.stock
            this.marketPriceMap[idx] = d.marketPrice
            this.coverMap[idx] = d.cover
            this.alertStockMap[idx] = d.alertStock
            this.goodsNoMap[idx] = d.goodsNo
            this.barCodeMap[idx] = d.barCode
            this.pointsMap[idx] = d.points
            this.otherImgsMap[idx] = d.otherImgs
            this.priceMap[idx] = d.price
            this.titleMap[idx] = d.title
            this.editableMap[idx] = true
            this.$set(this.enabledMap, key, true)
          } else {
            this.$set(this.enabledMap, key, false)
          }
        })
        console.log(this.stockMap)
      }
    },
    changeHasPic (item, index) {
      if (item.hasPic) {
        this.goodsRules.forEach((el, idx) => {
          if (idx !== index) {
            el.hasPic = false
          }
        })
      }
    },
    handleAvatarSuccess (item) {
      return (res, file) => {
        if (res && res.errcode === 0) {
          item.cover = res.info
        }
      }
    },
    priceIndex (row) {
      let rt = []
      for (let i = 0; i < row.length; i++) {
        rt.push(row[i].index)
      }
      return rt.join(',')
    },
    addNewGoodRule () {
      if (this.goodsRules.length === 0) {
        this.$emit('hasNewGoodRules')
      }
      this.goodsRules.push({
        title: '',
        // hasPic: false,
        inputVisible: false,
        inputValue: '',
        items: []
      })
      this.$nextTick(_ => {
        this.$refs['goodsRuleInput' + (this.goodsRules.length - 1)][0].focus()
      })
    },

    removeRule (index) {
      this.goodsRules.splice(index, 1)
      if (this.goodsRules.length === 0) {
        this.$emit('hasNoNewGoodRules')
      }
      this.goodsNoMap = {}
      this.barCodeMap = {}
      this.stockMap = {}
      this.priceMap = {}
      this.pointsMap = {}
      this.alertStockMap = {}
      this.marketPriceMap = {}
    },
    handleClose (index, yindex) {
      this.goodsRules[index].items.splice(yindex, 1)
      if (this.goodsRules[index].items.length === 0) {
        this.goodsNoMap = {}
        this.barCodeMap = {}
        this.stockMap = {}
        this.priceMap = {}
        this.pointsMap = {}
        this.alertStockMap = {}
        this.marketPriceMap = {}
      }
    },
    showInput (index) {
      this.goodsRules[index].inputVisible = true
      // this.$set(this.goodsRules[index],'inputVisible',true);
      this.$nextTick(_ => {
        this.$refs['saveTagInput' + index][0].focus()
      })
    },
    handleUploadCoverSuccess (res) {
      if (res.errcode == 0) {
        this.goodsCoverData.cover = res.info
      } else {
        this.$message.error(res.msg)
      }
    },

    handleInputConfirm (index) {
      let inputValue = this.goodsRules[index].inputValue
      if (inputValue) {
        this.goodsRules[index].items.push({
          title: inputValue
          // cover: ""
        })
        if (this.goodsRules[index].items.length === 1) {
          this.goodsNoMap = {}
          this.barCodeMap = {}
          this.stockMap = {}
          this.priceMap = {}
          this.coverMap = {}
          this.pointsMap = {}
          this.alertStockMap = {}
          this.marketPriceMap = {}
        }
      }
      this.goodsRules[index].inputVisible = false
      this.goodsRules[index].inputValue = '';
    }
  }
}
</script>

<style scoped>
.el-tag {
  width: 80px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: block;

  position: relative;
}

.el-tag >>> .el-tag__close {
  position: absolute;
  right: 5px;
  top: 7px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.el-tag-wrapper {
  display: inline-block;
  vertical-align: middle;
}

.el-tag-wrapper + .el-tag-wrapper {
  margin-left: 10px;
}

.goods-title {
  padding: 0;
}

.goods-title >>> .el-textarea__inner,
.goods-title >>> .el-input__inner {
  padding: 5px;
}

.avatar-uploader-2 {
  margin-top: 5px;

  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}
.disabled_tr {
  background-color: #eee;
  color: #aaa;
}
.avatar-uploader-3 {
  width: 82px;
  margin-top: 5px;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}

/* .goods-no {
  border: 1px solid #aaa;
  padding: 4px 6px;
  border-radius: 4px;
} */

.box-card {
  margin-bottom: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.price-and-stock table {
  margin-top: 20px;
  width: 100%;
  border-collapse: collapse;
  text-align: center;
}

.price-and-stock th {
  border: 1px solid #eee;
  padding: 15px 5px;
}

.price-and-stock td {
  border: 1px solid #eee;
  padding: 6px 5px;
}

.numberbox {
  width: 100px;
}

.right-icon {
  float: right;
}

.close-btn {
  cursor: pointer;
  margin-top: 10px;
  font-size: 16px;
}

.close-btn:hover {
  color: #409eff;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.batch {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
}
</style>
